package com.tanxiaoyao.wecon.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.*;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.tanxiaoyao.wecon.R;
import com.tanxiaoyao.wecon.app.AppManager;
import com.tanxiaoyao.wecon.app.AppSetting;
import com.tanxiaoyao.wecon.common.UIHelper;
import com.tanxiaoyao.wecon.net.BluetoothConnectService;
import com.tanxiaoyao.wecon.net.GlobalConnectHelper;

import java.util.HashMap;
import java.util.Iterator;

/**
 * 首页界面类
 *
 * @author tanxiaoyao (junlidev@gmail.com)
 * @version 2014/8/28 21:29.
 */
public class ActivityHome extends Activity {
	private static final int DISCOVERY_TIME = 120;
	private View home_header;
	private Button header_back_btn;
	private TextView home_header_title;
	private Button home_header_right_btn;

	// DEBUG标志
	private static final String TAG = "tanxiaoyao-home";
	private static final Boolean ISDEBUG = false;

	// intent请求码
	private static final int REQUEST_ENABLE_BT = 3;

	// 对话框显示当前搜索到的蓝牙设备
	private AlertDialog.Builder dialogBuilder;

	// 声明按钮
	private Button visi_blutoo_btn, scan_blutoo_btn, conn_blutoo_btn;
	// 滚动视图
	private ScrollView blutoo_state_scrollview;
	// 声明状态文字区
	public TextView blutoo_state_text;

	// 蓝牙适配器
	public static BluetoothAdapter btAdapter;
	// UUID码
	public static final String UUID = "00001101-0000-1000-8000-00805F9B34FB";
	// 蓝牙socket连接
	public static BluetoothSocket btSocket;
	// 蓝牙信息存储
	public static HashMap<String, String> blutooDevs;
	// 选中的蓝牙序号
	public static int checkedIndex;

	// 连接的设备名称
	private String connectedDevcieName;
	// 从后台服务传送过来的关键信息常量
	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast"; // 避免硬编码？？

	// 实例化全局连接助手
	GlobalConnectHelper globalConnector;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if(ISDEBUG) Log.i("xiaoyao", "Home onCreate");
		super.onCreate(savedInstanceState);
//      Activity压栈
      AppManager.getAppManager().addActivity(this);
		setContentView(R.layout.activity_home);
		// 得到标题栏View对象
		home_header = findViewById(R.id.main_header);
		// 隐藏返回按钮
		header_back_btn = (Button) home_header
				.findViewById(R.id.header_back_btn);
		header_back_btn.setVisibility(View.INVISIBLE);
		// 设置标题栏文字
		home_header_title = (TextView) findViewById(R.id.header_title);
		home_header_title.setText(R.string.home);
		// 设置右边按钮为摇一摇
		home_header_right_btn = (Button) findViewById(R.id.header_right_btn);
		home_header_right_btn.setText(R.string.shake4share);
		// TODO 实现摇一摇功能

		// 实例化蓝牙操作按钮
		visi_blutoo_btn = (Button) findViewById(R.id.bluetooth_visible_btn);
		scan_blutoo_btn = (Button) findViewById(R.id.scan_bluetooth_btn);
		conn_blutoo_btn = (Button) findViewById(R.id.connect_bluetooth_btn);
		// 实例化蓝牙适配器
		btAdapter = BluetoothAdapter.getDefaultAdapter();
		if (btAdapter == null) {
			UIHelper.Exit(this, this.getString(R.string.no_bluetooth));
			return;
		}// 后面在onStart中打开蓝牙

		// 实例化全局连接助手
		globalConnector = new GlobalConnectHelper();
		// 注册消息接收
		globalConnector.addHandler(homeHandler);
		// 实例化信息存储器
		blutooDevs = AppSetting.getBlutooDevInfo();
		// 实例化状态文本区
		blutoo_state_scrollview = (ScrollView) findViewById(R.id.blutoo_state_scrollview);
		blutoo_state_text = (TextView) findViewById(R.id.blutoo_state_text);
		// 监听文本改变并自动滚动到底部
		blutoo_state_text.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				// 设置自动滚到底部
				blutoo_state_scrollview.post(new Runnable() {
					@Override
					public void run() {
						blutoo_state_scrollview
								.fullScroll(ScrollView.FOCUS_DOWN);
					}
				});

			}
		});
		;

		// 按钮绑定监听器
		visi_blutoo_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) { // 设置蓝牙可见
				Intent visiIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
				visiIntent.putExtra(
						BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
						DISCOVERY_TIME);
				// 第二个参数是本机蓝牙被发现的时间，系统默认范围[1-300],超过范围默认300，小于范围默认120
				startActivity(visiIntent);
			}
		});
		scan_blutoo_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) { // 搜索蓝牙
				if (btAdapter.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没打开
					printStateText(getString(R.string.please_open_ble));
					Toast.makeText(getApplicationContext(),
							getString(R.string.please_open_ble),
							Toast.LENGTH_SHORT).show();
					return;
				}
				// 清空蓝牙的相关存储
				if (blutooDevs != null && !blutooDevs.isEmpty()) {
					blutooDevs.clear();
				}
				printStateText("本机蓝牙地址：" + btAdapter.getAddress());
				btAdapter.startDiscovery();
			}
		});
		conn_blutoo_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) { // 连接设备
				// 首先要检查蓝牙状况
				if (btAdapter == null && !btAdapter.isEnabled()) {
					printStateText(getString(R.string.please_open_ble));
					Toast.makeText(getApplicationContext(),
							getString(R.string.please_open_ble),
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (blutooDevs.isEmpty()) {
					printStateText(getString(R.string.devices_not_found));
					Toast.makeText(getApplicationContext(),
							getString(R.string.devices_not_found),
							Toast.LENGTH_SHORT).show();
				} else {
					// 这里开始连接设备
					// 获得设备名字数组
					Iterator<String> devIterator = blutooDevs.keySet()
							.iterator();
					final String devNameArray[] = new String[blutooDevs.size()];
					for (int i = 0; devIterator.hasNext(); i++) {
						devNameArray[i] = devIterator.next();
					}
					dialogBuilder = new AlertDialog.Builder(ActivityHome.this);
					dialogBuilder
							.setIcon(android.R.drawable.btn_dialog)
							.setSingleChoiceItems(devNameArray, 0,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialogInterface,
												int which) {
											checkedIndex = which;
										}
									})
							.setPositiveButton(R.string.confirm,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialogInterface,
												int i) {
											printStateText(getString(R.string.connecting_device)
													+ ":"
													+ devNameArray[checkedIndex]);
											// TODO 注意这里及时销毁对话框资源
											// 获得设备地址
											String devAddress = blutooDevs.get(
													devNameArray[checkedIndex])
													.toString();
											// 开启后台连接线程
											globalConnector.connectDevice(
													btAdapter, devAddress);
										}
									})
							.setNegativeButton(R.string.cancle,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialogInterface,
												int i) {
											// TODO 注意这里及时销毁对话框资源
										}
									}).setTitle(R.string.choose_device);
					dialogBuilder.create().show();

				}
			}
		});

		// 注册接收系统蓝牙消息的接收器
		IntentFilter intent = new IntentFilter();
		intent.addAction(BluetoothDevice.ACTION_FOUND);// 远程设备发现动作。
		intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);// 远程设备的键态的变化动作。
		intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);// 蓝牙扫描本地适配器模改变动作。
		intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);// 状态改变动作
		registerReceiver(searchDevices, intent);// 注册接收

	}

	/**
	 * 向文本区打印状态日志
	 * 
	 * @param stateMsg
	 *            日志内容
	 */
	private void printStateText(String stateMsg) {
		blutoo_state_text.append(stateMsg + "\n");
	}

	/**
	 * 消息处理
	 */
	Handler homeHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) { // 判断发送的消息类型
			case GlobalConnectHelper.MESSAGE_STATE_CHANGE:
				if (ISDEBUG)
					if(ISDEBUG) Log.d(TAG, "###get msg:state change -> " + msg.arg1 + "###");
				switch (msg.arg1) {
				case BluetoothConnectService.STATE_CONNECTED:
					// 打印连接设备
					printStateText(getString(R.string.connect_to)
							+ connectedDevcieName);
					break;
				case BluetoothConnectService.STATE_CONNECTING:
					printStateText(getString(R.string.connecting));
					break;
				case BluetoothConnectService.STATE_LISTEN:
					printStateText(getString(R.string.listening));
					break;
				case BluetoothConnectService.STATE_NONE:
					printStateText(getString(R.string.state_none));
					break;
				default:
					break;
				}
				break;
			// case GlobalConnectHelper.MESSAGE_WRITE: // 将后台写入的消息打印到list
			// byte[] writeBuf = (byte[]) msg.obj;
			// // 从字节建立字符串
			// String writeMessage = new String(writeBuf);
			// conversationArrayAdapter.add(getString(R.string.i_say)
			// + writeMessage);
			// break;
			// case GlobalConnectHelper.MESSAGE_READ: // 从后台读取消息，并刷新在主界面上
			// byte[] readBuf = (byte[]) msg.obj;
			// // 同理，建立字符串（根据正确的长度）并显示
			// String readMessage = new String(readBuf, 0, msg.arg1);
			// conversationArrayAdapter.add(getString(R.string.you_say)
			// + readMessage);
			// break;
				
			case GlobalConnectHelper.MESSAGE_READ:
				// 更新界面文本
				printStateText(">>>收到消息：" + msg.obj);
				break;
			case GlobalConnectHelper.MESSAGE_DEVICE_NAME:
				// 赋值给成员变量（通过键值对传送字符串）
				connectedDevcieName = (String) msg.obj;
				Toast.makeText(getApplicationContext(),
						getString(R.string.connect_to) + connectedDevcieName,
						Toast.LENGTH_LONG).show();
				break;
			case GlobalConnectHelper.MESSAGE_TOAST: // 直接显示它想显示的信息
				Toast.makeText(getApplicationContext(), getString(msg.arg1),
						Toast.LENGTH_LONG).show();
				printStateText(getString(msg.arg1));
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	/**
	 * 蓝牙动作监听
	 */
	private BroadcastReceiver searchDevices = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// 搜索设备时，获得设备的MAC地址
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// 取得外部搜索到的蓝牙设备
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				// 更新界面文本
				printStateText("发现设备：" + device.getName() + "  MAC："
						+ device.getAddress());
				// 存储搜索到的蓝牙
				blutooDevs.put(device.getName(), device.getAddress()); // 存储设备名，地址
			}
		}
	};

	/**
	 * 重新开启该页面是检查蓝牙是否被中途关闭
	 */
	@Override
	protected void onStart() {
		if (btAdapter != null) {
			if (!btAdapter.isEnabled()) {
				// 重新打开蓝牙
				Intent enableIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
			} else {
				if (!globalConnector.hasService()) {
					// 建立蓝牙连接对象
					globalConnector.creatConnectService();
				}
			}
		}
		super.onStart();
	}

	/**
	 * 请求跳转结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (ISDEBUG)
			if(ISDEBUG) Log.d(TAG, "onActivityResult " + resultCode);
		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			// 当在onstart界面请求打开蓝牙同意后
			if (resultCode == Activity.RESULT_OK) {
				// 蓝牙打开，建立连接（蓝牙重新打开肯定要重新建立连接）
				// 建立蓝牙连接对象，这里的建立对象是为了使用连接方法，我们把它封装到连接Helper里去
				globalConnector.creatConnectService();
			} else {
				// 用户拒绝了打开蓝牙
				if (ISDEBUG)
					if(ISDEBUG) Log.d(TAG, "user refuse to open ble");
				UIHelper.Exit(this, getString(R.string.user_refuse_open));
			}
		}
	}

	/**
	 * 恢复时检查蓝牙连接服务
	 */
	@Override
	public synchronized void onResume() {
		// 检查连接
		if (globalConnector != null
				&& globalConnector.hasService()) {
			if (globalConnector.getServiceState() == BluetoothConnectService.STATE_NONE) {
				globalConnector.startService();
			}
		}
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if(ISDEBUG) Log.i("xiaoyao", "Home onDestroy");
		// 销毁接收器(前提是该接收器被注册了)
		if (searchDevices.isOrderedBroadcast())
			this.unregisterReceiver(searchDevices);
		super.onDestroy();
	}

}